import axios from "axios";
import {Message} from "tdesign-mobile-vue";
import router from "@/router";
import {useUserStore} from "@/stores/user"

const store = useUserStore()

axios.defaults.baseURL = import.meta.env.VITE_BASE_URL;
axios.defaults.timeout = 30000;
const http = axios.create();

http.interceptors.request.use((config) => {
    const token = store.token;
    if (token) {
        config.headers = {
            Authorization: token, ...config.headers
        }
    }
    return config;
}, (error) => {
    Message.error({
        content: error, icon: true, zIndex: 2005008, offset: [10, 16]
    })
    return Promise.reject(error);
})

http.interceptors.response.use(response => {
    if (response.status === 200) {
        const {code, msg} = response.data;
        if (code === 401) {
            Message.error({
                content: msg, context: document.querySelector('body'), offset: [8, 8]
            })
            setTimeout(() => {
                localStorage.clear()
                router.replace({name: 'login'})
            }, 2000)
        } else if (code === 403) {
            Message.error({
                content: msg, context: document.querySelector('body'), offset: [8, 8]
            })
            setTimeout(() => {
                localStorage.clear()
                router.back()
            }, 2000)
        }
    } else if (response.status === 500) {
        Message.error({
            content: '服务器错误\n' + response.data, context: document.querySelector('body'), offset: [8, 8]
        })
    }
    return response;
}, error => {
    console.log(error);
    return Promise.reject(error);
})

export default http;